package com.projectmanagement.view;

import com.projectmanagement.PMApplication;
import com.projectmanagement.helpers.Auth;
import com.projectmanagement.helpers.i18n.TM;
import com.projectmanagement.model.data.User;
import com.projectmanagement.view.admin.AdminWindow;
import com.projectmanagement.view.client.ClientWindow;
import com.projectmanagement.view.user.UserWindow;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.CustomLayout;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.TextField;
import com.vaadin.ui.Window;

public class Login extends Window {

	private static final long serialVersionUID = -6338788274779364886L;

	
	private CustomLayout loginWindow;
	private TextField username;
	private PasswordField password;
	private Button login;

	public Login() {
		super();
		init();
	}

	private void init() {
//		setSizeFull();
		loginWindow = new CustomLayout("login");
		
//		loginWindow.setMargin(false);

		
//		CSSInject css = new CSSInject();
//		css.setValue("body{	background: url(images/bg_punched.png) repeat fixed !important;}");
//		
//		addComponent(css);
//	
		setContent(loginWindow);
	}
	
	@Override
	public void attach() {
		super.attach();
		
		
		
		
		username = new TextField(TM.get(getApplication(), "app.username"));
		password = new PasswordField(TM.get(getApplication(), "app.password"));
		login = new Button(TM.get(getApplication(), "app.login"));
		
		login.addListener(new Button.ClickListener() {
			private static final long serialVersionUID = -4997008603803159289L;

			@Override
			public void buttonClick(ClickEvent event) {
				authenticate();
			}
		});
		
//		addComponent(username);
//		addComponent(password);
//		addComponent(login);
	}
	
	private void authenticate(){
		User user = Auth.login(username.toString(), password.toString());
		PMApplication app = PMApplication.getInstance();
		
		if(user != null){
			if(user.getUserType().equals("admin")){
				app.setView(new AdminWindow());
			}else if(user.getUserType().equals("user")){
				app.setView(new UserWindow());
			}else{
				app.setView(new ClientWindow());
			}
		}
		else{
			System.out.println("error");
			app.setView(new ClientWindow());
		}
	}
	
	
}
